package com.the_ring.chapter11.widget;

import android.content.Context;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

public class BannerPager extends View {

    private float mOffsetX, mOffsetY;
    private PointF mLastPos;

    public BannerPager(Context context) {
        this(context, null);
    }

    public BannerPager(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean result = true;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            mOffsetX = 0.0f;
            mOffsetY = 0.0f;
            mLastPos = new PointF(event.getX(), event.getY());
            result = super.onTouchEvent(event);
        } else {
            PointF thisPos = new PointF(event.getX(), event.getY());
            mOffsetX += Math.abs(thisPos.x - mLastPos.x);
            mOffsetY = Math.abs(thisPos.y - mLastPos.y);
            mLastPos = thisPos;
            if (mOffsetX >= mOffsetY) {
                // 如果外层是普通的 ScrollView，则此处不允许父容器的拦截动作
                // CustomScrollActivity 通过自定义滚动视图来区分水平滑动和垂直滑动
                // DisallowScrollActivity 使用股东视图，则需要下面的代码禁止父容器拦截
                getParent().requestDisallowInterceptTouchEvent(true);
                result = true;
            } else {
                result = false;
            }
        }
        return result;
    }
}
